import { Component, Input, OnInit } from '@angular/core';
import { FormArray, FormGroup } from '@angular/forms';
import { isNumber } from 'lodash';

@Component({
  selector: 'app-item-error',
  templateUrl: './item-error.component.html',
  styleUrls: ['./item-error.component.scss'],
})
export class ItemErrorComponent implements OnInit {
  @Input() form: FormGroup;
  @Input() name: string;
  @Input() index: number;
  constructor() {}

  get ctrl() {
    if (isNumber(this.index)) {
      const array = this.form.get(this.name) as FormArray;
      return array.controls[this.index];
    }

    return this.form.get(this.name);
  }

  get show() {
    const ctrl = this.ctrl;
    if (ctrl) {
      return ctrl.invalid && (ctrl.dirty || ctrl.touched);
    }

    return false;
  }

  error(key: string) {
    return this.ctrl?.errors?.[key];
  }

  ngOnInit() {}
}
